package org.jupiter.blog.service.service.impl;

import org.jupiter.blog.api.convertor.JupiterCommentConvertor;
import org.jupiter.blog.api.domain.JupiterComment;
import org.jupiter.blog.api.dto.JupiterCommentDTO;
import org.jupiter.blog.service.mapper.JupiterCommentMapper;
import org.jupiter.blog.service.service.JupiterCommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Service
public class JupiterCommentServiceImpl implements JupiterCommentService {

	@Autowired
	private JupiterCommentMapper commentMapper;
	@Autowired
	private JupiterCommentConvertor commentConvertor;

	@Transactional
	@Override
	public void createComment(JupiterCommentDTO dto) {
		JupiterComment comment = commentConvertor.toEntity(dto);
		if (comment.getUuid() == null){
			comment.setUuid(UUID.randomUUID().toString());
		}
		comment.setCreateTime(LocalDateTime.now());
		commentMapper.insert(comment);
	}

	@Override
	public JupiterCommentDTO getById(String uuid) {
		JupiterComment comment = commentMapper.selectByUuid(uuid);
		return commentConvertor.toDto(comment);
	}

	@Override
	public List<JupiterCommentDTO> getByPage(JupiterCommentDTO queryDTO) {
		int offset = (queryDTO.getPage() - 1) * queryDTO.getSize();
		List<JupiterComment> comments = commentMapper.selectByPage(
				queryDTO.getUuid(), queryDTO.getArticleId(), queryDTO.getUserId(),
				queryDTO.getParentId(), queryDTO.getIsStick(), offset, queryDTO.getSize()
		);
		return comments.stream()
				.map(commentConvertor::toDto)
				.toList();
	}

	@Override
	public List<JupiterCommentDTO> getCommentsByArticleId(String articleId) {
		List<JupiterComment> comments = commentMapper.selectByArticleId(articleId);
		return comments.stream()
				.map(commentConvertor::toDto)
				.toList();
	}

	@Override
	@Transactional
	public boolean deleteComment(String uuid) {
		commentMapper.deleteByUuid(uuid);
		return false;
	}

	@Override
	@Transactional
	public int likeComment(String uuid) {
		return commentMapper.likeComment(uuid);
	}
}
